import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../textFiled/kq_textfiled.dart';

/// 步进数字条
///
/// 支持输入数字，加减数字A。
///
/// @author 周卓
class KqStepNumberBar extends StatefulWidget {
  /// 步进值，默认1
  final num step;

  /// 最小值，默认0
  final num min;

  /// 最大值
  final num? max;

  /// 是否支持小数，默认false
  final bool decimal;

  /// 是否可编辑
  final bool editable;

  /// 输入框内容控制器
  final TextEditingController editController;

  /// 数字变化回调
  final Function(num value, String formatValue)? onValueChanged;

  const KqStepNumberBar(
      {Key? key,
      this.decimal = false,
      this.editable = true,
      required this.editController,
      this.min = 0,
      this.step = 1,
      this.max,
      this.onValueChanged})
      : super(key: key);

  @override
  KqStepNumberBarState createState() => KqStepNumberBarState();
}

class KqStepNumberBarState extends State<KqStepNumberBar> {
  late num qty;
  late String qtyString;

  @override
  void initState() {
    qty = num.tryParse(widget.editController.text) ?? widget.min;
    qtyString = widget.editController.text;
    if (qtyString.isEmpty) {
      qtyString = widget.min.toString();
    }
    super.initState();
  }

  @override
  void didUpdateWidget(covariant KqStepNumberBar oldWidget) {
    qty = num.tryParse(widget.editController.text) ?? widget.min;
    qtyString = widget.editController.text;
    if (qtyString.isEmpty) {
      qtyString = widget.min.toString();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        /// 数量减
        InkWell(
          onTap: () => _onDec(),
          child: Image.asset(
            _decAble()
                ? Images.commonIcReduceNormal
                : Images.commonIcReduceDisabled,
            width: 32.r,
            height: 26.r,
            fit: BoxFit.fill,
            package: KqGlobal.packageName,
          ),
        ),
        SizedBox(
          width: 4.r,
          height: 1,
        ),

        /// 数量输入框
        SizedBox(
          width: 46.r,
          child: KqTextFiled(
            inputType: TextInputType.numberWithOptions(decimal: widget.decimal),
            multiline: false,
            maxLines: 1,
            enableClearButton: false,
            editable: widget.editable,
            textAlign: TextAlign.center,
            fontSize: KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .contentFontSize ??
                16.sp,
            controller: widget.editController,
            placeHolder: widget.min.toString(),
            inputFormatters: widget.decimal
                ? TextInputFormatUtils.decimal()
                : TextInputFormatUtils.maxInter(
                    widget.max?.toInt() ?? 999999999,
                    min: widget.min.toInt()),
            onChanged: (value) => _onValueChanged(value),
          ),
        ),
        SizedBox(
          width: 4.r,
          height: 1,
        ),

        /// 数量加
        InkWell(
          onTap: () => _onPlus(),
          child: Image.asset(
            _addAble()
                ? Images.commonIcIncreaseNormal
                : Images.commonIcIncreaseDisabled,
            width: 32.r,
            height: 26.r,
            fit: BoxFit.fill,
            package: KqGlobal.packageName,
          ),
        ),
      ],
    );
  }

  /// 点击减号
  void _onDec() {
    if ((qty - widget.step) >= widget.min) {
      _onValueChanged((qty - widget.step).toString());
    }
  }

  /// 点击加号
  void _onPlus() {
    if (widget.max == null || (qty + widget.step) <= widget.max!) {
      _onValueChanged((qty + widget.step).toString());
    }
  }

  /// 输入框数值变化
  void _onValueChanged(String text) {
    qtyString = text;
    qty = text.isEmpty ? widget.min : num.parse(text);
    if (qty < widget.min) {
      qty = widget.min;
      qtyString = widget.min.toString();
    } else if (widget.max != null) {
      if (qty > widget.max!) {
        qty = widget.max!;
        qtyString = widget.max!.toString();
      }
    }
    widget.editController.text = qtyString;
    widget.onValueChanged?.call(qty, qtyString);
    setState(() {

    });
  }

  // 减号能不能点
  bool _decAble() {
    return (qty - widget.step) >= widget.min;
  }

  // 加号能不能点
  bool _addAble() {
    return widget.max == null || (qty + widget.step) <= widget.max!;
  }
}
